package com.sinosoft.perfect.system._user.service;

import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sinosoft.perfect.system._.po.TUser;
import com.sinosoft.perfect.system._.po.TUserImg;
import com.sinosoft.perfect.system._.po.TUserInformation;
import com.sinosoft.perfect.system._.po.TUserRolebusinessRelation;
import com.sinosoft.perfect.system._.po.TUserRolesysRelation;
import com.sinosoft.perfect.system._.po.TUserUnitRelation;
import com.sinosoft.perfect.system._.service.ISortNumberService;
import com.sinosoft.perfect.system._.util.Producer;
import com.sinosoft.perfect.system._.util.SystemUtil;
import com.sinosoft.perfect.system._.vo.SortNumber;
import com.sinosoft.perfect.system._display.service.IDisplayService;
import com.sinosoft.perfect.system._theme.dao.IThemeDAO;
import com.sinosoft.perfect.system._user.dao.IUserDAO;
import com.sinosoft.perfect.system._user.formBean.UserForm;
import com.sinosoft.perfect.system._user.vo.UserStaticVO;
import com.sinosoft.perfect.system._user.vo.UserUnitVO;

public class UserServiceImpl implements IUserService {

	private IUserDAO userDAO;

	private IThemeDAO themeDAO;

	private IDisplayService displayService;

	private ISortNumberService sortNumberService;

	public IUserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public IThemeDAO getThemeDAO() {
		return themeDAO;
	}

	public void setThemeDAO(IThemeDAO themeDAO) {
		this.themeDAO = themeDAO;
	}

	public IDisplayService getDisplayService() {
		return displayService;
	}

	public void setDisplayService(IDisplayService displayService) {
		this.displayService = displayService;
	}

	public ISortNumberService getSortNumberService() {
		return sortNumberService;
	}

	public void setSortNumberService(ISortNumberService sortNumberService) {
		this.sortNumberService = sortNumberService;
	}

	public List<UserStaticVO> selectTUserStatic(UserStaticVO userStatic) throws SQLException {
		return userDAO.selectTUserStatic(userStatic);
	}

	public String insertTUser(String unitId, TUser tuser) throws Exception {
		String id = Producer.generateIdOfTen();
		tuser.setUserMainId(id);
		tuser.setLoginPassword(SystemUtil.md5(tuser.getLoginPassword()));
		tuser.setCreateUserId("1");
		tuser.setUserType("1");

		tuser.setFrameModelId(displayService.selectTDisplayDefault().getFrameModelId());
		tuser.setThemeId((String) themeDAO.selectTThemeDefault());
		tuser.setStatus("1");
		userDAO.insertTUser(tuser);

		TUserInformation tuserinfo = new TUserInformation();
		tuserinfo.setId(Producer.generateIdOfTen());
		tuserinfo.setUserMainId(id);
		userDAO.insertTUserInfo(tuserinfo);

		TUserImg tuserimg = new TUserImg();
		tuserimg.setId(Producer.generateIdOfTen());
		tuserimg.setUserMainId(id);
		userDAO.insertTUserImg(tuserimg);

		int sortNum = this.selectTUserMAXSortNumFromUnit(unitId) + 1;
		TUserUnitRelation tuserunit = new TUserUnitRelation();
		tuserunit.setUserSortNumber(new Long(sortNum));
		tuserunit.setUnitId(unitId);
		tuserunit.setUserMainId(id);
		this.insertTUserUnit(tuserunit);
		return id;
	}

	public String insertTUserUnit(TUserUnitRelation tuserunit) throws SQLException {
		int sortNum = this.selectTUserMAXSortNumFromUnit(tuserunit.getUnitId()) + 1;
		String id = Producer.generateIdOfTen();
		tuserunit.setManageId(id);
		tuserunit.setUserSortNumber(new Long(sortNum));
		userDAO.insertTUserUnit(tuserunit);
		return id;
	}

	public void insertTUsersUnit(String unitId, String userIds) throws SQLException {
		int sortNum = this.selectTUserMAXSortNumFromUnit(unitId) + 1;
		userIds = userIds.substring(0, userIds.lastIndexOf(','));
		if (userIds.indexOf(',') != -1) {
			String[] uIds = userIds.split(",");
			for (int i = 0; i < uIds.length; i++, sortNum++) {
				TUserUnitRelation tuserunit = new TUserUnitRelation();
				tuserunit.setUnitId(unitId);
				tuserunit.setUserMainId(uIds[i]);
				tuserunit.setUserSortNumber(new Long(sortNum));
				this.insertTUserUnit(tuserunit);
			}
		} else {
			TUserUnitRelation tuserunit = new TUserUnitRelation();
			tuserunit.setUnitId(unitId);
			tuserunit.setUserMainId(userIds);
			tuserunit.setUserSortNumber(new Long(sortNum));
			this.insertTUserUnit(tuserunit);
		}
	}

	public void insertTUserUnits(String userId, String unitIds) throws SQLException {
		if (unitIds.indexOf(",") != -1) {
			String[] uIds = unitIds.split(",");
			for (int i = 0; i < uIds.length; i++) {
				int sortNum = this.selectTUserMAXSortNumFromUnit(uIds[i]) + 1;
				TUserUnitRelation tuserunit = new TUserUnitRelation();
				tuserunit.setUnitId(uIds[i]);
				tuserunit.setUserMainId(userId);
				tuserunit.setUserSortNumber(new Long(sortNum));
				this.insertTUserUnit(tuserunit);
			}
		} else {
			int sortNum = this.selectTUserMAXSortNumFromUnit(unitIds) + 1;
			TUserUnitRelation tuserunit = new TUserUnitRelation();
			tuserunit.setUnitId(unitIds);
			tuserunit.setUserMainId(userId);
			tuserunit.setUserSortNumber(new Long(sortNum));
			this.insertTUserUnit(tuserunit);
		}
	}

	public String insertTUserRoleBusiness(TUserRolebusinessRelation tuserrolebusiness) throws SQLException {
		String id = Producer.generateIdOfTen();
		tuserrolebusiness.setManageId(id);
		int sortNum = this.selectTUserMAXSortNumFromRoleBusiness(tuserrolebusiness.getRoleBusinessId()) + 1;
		tuserrolebusiness.setUserSortNumber(new Long(sortNum));
		userDAO.insertTUserRoleBusiness(tuserrolebusiness);
		return id;
	}

	public List<TUser> selectTUser(TUser tuser) throws SQLException {
		return userDAO.selectTUser(tuser);
	}

	public List<UserForm> selectTUserFromUnit(UserForm userForm) throws SQLException {
		return userDAO.selectTUserFromUnit(userForm);
	}

	public List<UserForm> selectTUserFromRoleBusiness(UserForm userForm) throws SQLException {
		return userDAO.selectTUserFromRoleBusiness(userForm);
	}

	public int selectExistTUser(UserForm userform) throws SQLException {
		return (userDAO.selectExistTUser(userform) != null ? 1 : 0);
	}

	public boolean selectExistTUserFromUnit(String userId, String unitId) throws SQLException {
		boolean result = false;
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("unitId", unitId);
		Object obj = userDAO.selectExistTUserFromUnit(map);
		if (obj != null)
			result = true;
		return result;
	}

	public boolean selectExistTUserFromRoleBusiness(String userId, String roleBusinessId) throws SQLException {
		boolean result = false;
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("roleBusinessId", roleBusinessId);
		Object obj = userDAO.selectExistTUserFromRoleBusiness(map);
		if (obj != null)
			result = true;
		return result;
	}

	public int selectExistTUserForUpdate(TUser user) throws SQLException {
		return (userDAO.selectExistTUserForUpdate(user) != null ? 1 : 0);
	}

	public Long selectTUserSortNumFromUnit(String unitId, String userId) throws SQLException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("unitId", unitId);
		map.put("userId", userId);
		Long sortNum = null;
		Object numObj = userDAO.selectTUserSortNumFromUnit(map);
		if (numObj != null)
			sortNum = Long.parseLong(numObj.toString());
		return sortNum;
	}

	public Integer selectTUserMAXSortNumFromUnit(String unitId) throws SQLException {
		Integer sortNum = 0;
		Object numObj = userDAO.selectTUserMAXSortNumFromUnit(unitId);
		if (numObj != null)
			sortNum = Integer.parseInt(numObj.toString());
		return sortNum;
	}

	public Long selectTUserSortNumFromRoleBusiness(String roleBusinessId, String userId) throws SQLException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("roleBusinessId", roleBusinessId);
		map.put("userId", userId);
		Long sortNum = null;
		Object numObj = userDAO.selectTUserSortNumFromRoleBusiness(map);
		if (numObj != null)
			sortNum = Long.parseLong(numObj.toString());
		return sortNum;
	}

	public Integer selectTUserMAXSortNumFromRoleBusiness(String roleBusinessId) throws SQLException {
		Integer sortNum = 0;
		Object numObj = userDAO.selectTUserMAXSortNumFromRoleBusiness(roleBusinessId);
		if (numObj != null)
			sortNum = Integer.parseInt(numObj.toString());
		return sortNum;
	}

	public List<UserUnitVO> selectTUserAndTUnit(String unitId) throws SQLException {
		return userDAO.selectTUserAndTUnit(unitId);
	}

	public List<TUserInformation> selectTUserInfo(TUserInformation tuserinfo) throws SQLException {
		return userDAO.selectTUserInfo(tuserinfo);
	}

	public List<TUserImg> selectTUserImg(TUserImg tuserimg) throws SQLException {
		return userDAO.selectTUserImg(tuserimg);
	}

	public List<TUser> selectTUserDetached(TUser tuser) throws SQLException {
		return userDAO.selectTUserDetached(tuser);
	}

	public String selectTUserName(String userMainId) throws SQLException {
		return (String) userDAO.selectTUserNameFromUserOrUserInfo(userMainId);
	}

	public void updateTUserByPK(TUser tuser) throws Exception {
		if (tuser.getLoginPassword() != null && !"".equals(tuser.getLoginPassword())) {
			tuser.setLoginPassword(SystemUtil.md5(tuser.getLoginPassword()));
		}
		userDAO.updateTUserByPK(tuser);
	}

	public void updateTUserInfoByPK(TUserInformation tuserinfo) throws SQLException {
		userDAO.updateTUserInfoByPK(tuserinfo);
	}

	public void updateTUserImg(TUserImg tuserimg) throws SQLException {
		String userMainId = tuserimg.getUserMainId();
		TUserImg img = new TUserImg();
		img.setUserMainId(userMainId);
		List<TUserImg> userImgs = userDAO.selectTUserImg(img);
		if (userImgs != null && userImgs.size() > 0) {
			userDAO.updateTUserImg(tuserimg);
		} else {
			tuserimg.setId(Producer.generateIdOfTen());
			userDAO.insertTUserImg(tuserimg);
		}
	}

	public boolean deleteTUserAll(String userId) {
		boolean result = false;
		try {
			TUserRolesysRelation tuserrolesys = new TUserRolesysRelation();
			tuserrolesys.setUserMainId(userId);
			userDAO.deleteTUserRoleSystem(tuserrolesys);

			TUserRolebusinessRelation tuserrolebusiness = new TUserRolebusinessRelation();
			tuserrolebusiness.setUserMainId(userId);
			userDAO.deleteTUserRoleBusiness(tuserrolebusiness);

			TUserUnitRelation tuserunit = new TUserUnitRelation();
			tuserunit.setUserMainId(userId);

			userDAO.deleteTUserUnit(tuserunit);
			userDAO.deleteTUserImg(userId);
			userDAO.deleteTUserInfo(userId);
			userDAO.deleteTUser(userId);
			result = true;

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public boolean deleteTUserUnit(String userId, String unitId) {
		boolean result = false;
		TUserUnitRelation tuserunit = new TUserUnitRelation();
		tuserunit.setUserMainId(userId);
		tuserunit.setUnitId(unitId);
		try {
			userDAO.deleteTUserUnit(tuserunit);
			result = true;

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void deleteTUserRoleBusiness(String userId, String roleBusinessId) throws SQLException {
		TUserRolebusinessRelation tuserrolebusiness = new TUserRolebusinessRelation();
		tuserrolebusiness.setUserMainId(userId);
		tuserrolebusiness.setRoleBusinessId(roleBusinessId);
		userDAO.deleteTUserRoleBusiness(tuserrolebusiness);
	}

	public int validatePassword(TUser user) throws SQLException, NoSuchAlgorithmException {
		String md5Password = SystemUtil.md5(user.getLoginPassword());
		user.setLoginPassword(md5Password);
		int result = Integer.parseInt(userDAO.selectExistTUserPassword(user).toString());
		return result;
	}

	public boolean sortUserInUnit(long newSortNumber, String userId, String unitId) throws SQLException {
		SortNumber sortNumber = new SortNumber(newSortNumber, userId, unitId, "T_USER_UNIT_RELATION", "USER_MAIN_ID", "UNIT_ID", "USER_SORT_NUMBER");
		sortNumberService.sortNumberRelation(sortNumber);
		return false;
	}

	public boolean sortUserInRoleBusiness(long newSortNumber, String userId, String roleBusinessId) throws SQLException {
		SortNumber sortNumber = new SortNumber(newSortNumber, userId, roleBusinessId, "T_USER_ROLEBUSINESS_RELATION", "USER_MAIN_ID", "ROLE_BUSINESS_ID", "USER_SORT_NUMBER");
		sortNumberService.sortNumberRelation(sortNumber);
		return false;
	}

	@Override
	public List<TUser> selectTUsersInfoByUserids(String userids) throws SQLException {
		return userDAO.selectTUsersInfoByUserids(userids);
	}

	@Override
	public int insertAndDeleteUsersToUnit(String addUserIds, String delUserIds, String unitId) throws SQLException {
		int flag = -1;
		if(delUserIds != null && !"".equals(delUserIds)) {
			String[] delIds = delUserIds.split(",");
			for (int i = 0; i < delIds.length; i++) {
				this.deleteTUserUnit(delIds[i], unitId);
				flag++;
			}
		}
		if(addUserIds != null && !"".equals(addUserIds)) {
			String[] addIds = addUserIds.split(",");
			for (int i = 0; i < addIds.length; i++) {
				if(selectExistTUserFromUnit(addIds[i], unitId)){
					continue;
				} else {
					TUserUnitRelation tuserunit = new TUserUnitRelation();
					tuserunit.setUserMainId(addIds[i]);
					tuserunit.setUnitId(unitId);
					this.insertTUserUnit(tuserunit);
				}
				flag++;
			}
		}
		return flag;
	}

	@Override
	public List<UserForm> selectTUserFromRoleSystem(String roleSystemId) throws SQLException {
		return userDAO.selectTUserFromRoleSystem(roleSystemId);
	}
}
